import { useState, useEffect, useRef, useCallback } from "react";
import QRCode from "qrcode";
import JsBarcode from "jsbarcode";

export const usePaymentCodes = (baseValue) => {
  const [qrCodeUrl, setQrCodeUrl] = useState("");
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState(null);
  const barcodeRef = useRef(null);

  const generateCodes = useCallback(async () => {
    if (!baseValue) return;

    setIsGenerating(true);
    setError(null);

    try {
      const uniqueValue = baseValue;
      // 生成二维码
      const qrUrl = await QRCode.toDataURL(uniqueValue, {
        width: 180,
        margin: 1,
        color: {
          dark: "#000000",
          light: "#FFFFFF",
        },
        errorCorrectionLevel: "H",
      });

      setQrCodeUrl(qrUrl);

      // 生成条形码
      if (barcodeRef.current) {
        barcodeRef.current.innerHTML = "";

        await new Promise((resolve) => {
          setTimeout(() => {
            try {
              JsBarcode(barcodeRef.current, uniqueValue, {
                format: "CODE128",
                width: 2.8,
                height: 40,
                displayValue: false,
                background: "transparent",
                lineColor: "#000000",
              });
              resolve();
            } catch (err) {
              console.error("条形码生成失败:", err);
              resolve();
            }
          }, 50);
        });
      }
    } catch (err) {
      console.error("支付码生成失败:", err);
      setError(err.message || "生成失败");
    } finally {
      setIsGenerating(false);
    }
  }, [baseValue]);

  const refreshCodes = useCallback(() => {
    generateCodes();
  }, [generateCodes]);

  useEffect(() => {
    generateCodes();
  }, [generateCodes]);

  const imgDestroy = useCallback(() => {
    setQrCodeUrl("");
    barcodeRef.current = null;
  }, []);

  return {
    qrCodeUrl,
    barcodeRef,
    isGenerating,
    error,
    refreshCodes,
    imgDestroy,
  };
};
